package com.wing.api.add.user.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wing.api.ApplicationContextUtil;
import com.wing.api.add.user.BaseUserService;
import com.wing.cabinet.model.response.EnterpricceIdVO;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.Result;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.Role;
import com.wing.user.model.request.User;
import com.wing.user.model.response.CompanyInfoVO;
import com.wing.user.model.response.DepartmentVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 标准用户接口
 */
@Service
@Slf4j
public class StandardUserServiceImpl implements BaseUserService {

    @Override
    public void logicProcess(JSONObject jsonObject, EnterpricceIdVO enterpricceIdVo) throws IOException {
        log.info("请求参数,{}", jsonObject.toJSONString());
        //此处需要做接口签名验证
        //sign = md5（参数1+参数2+参数3+key）
        String sourceSign = jsonObject.getString("sign"); // 签名值
        JSONArray data = jsonObject.getJSONArray("data"); //业务数据
        if(StringUtils.isBlank(sourceSign)){
            throw new BusinessException("签名值为空！");
        }
        if(StringUtils.isBlank(data.toJSONString())){
            throw new BusinessException("请求参数为空！");
        }
        /*log.info("签名源串,{}", sourceSign);
        String desSign = DigestUtil.md5Hex("companyName" +"departmentName" +"postName" +"username"+ enterpricceIdVo.getKey());
        log.info("签名目的串,{}", desSign);
        if(!desSign.equals(sourceSign)){
            throw new BusinessException("签名不通过！");
        }*/

        StringBuffer tempStr = new StringBuffer();
        tempStr.append(data);
        tempStr.append(enterpricceIdVo.getKey());
        log.info("签名源串,{}", sourceSign);
        String desSign = DigestUtil.md5Hex(tempStr.toString());
        log.info("签名目的串,{}", desSign);
        if(!desSign.equals(sourceSign)){
            throw new BusinessException("签名不通过！");
        }
        UserClient userClient = (UserClient) ApplicationContextUtil.getBean("userClientFallback");
        //业务逻辑
        for (int i = 0; i < data.size(); i++) {
            JSONObject jsonObj = data.getJSONObject(i);
            String companyName = jsonObj.getString("companyName");
            if(StringUtils.isEmpty(companyName)){
                throw new BusinessException("第" + (i+1) +  "所属企业不能为空！");
            }
            JsonResult<CompanyInfoVO> companyJsonResult = userClient.getCompanyByName(companyName);
            if(companyJsonResult.getData().getId() == null){
                throw new BusinessException("第" + (i+1) +"当前企业不存在，请先同步企业数据！");
            }
            String departmentName = jsonObj.getString("departmentName");
            if(StringUtils.isEmpty(departmentName)){
                throw new BusinessException("第" + (i+1) +  "行部门名称不能为空！");
            }
            JsonResult<DepartmentVO> departmentJsonResult = userClient.getDepartmentByName(departmentName,null,companyJsonResult.getData().getId());
            if(departmentJsonResult.getData().getId() == null){
                throw new BusinessException("第" + (i+1) + "该部门:"+departmentName+"数据不存在！");
            }

            String postName = jsonObj.getString("postName");
            if(StringUtils.isEmpty(postName)){
                throw new BusinessException("第" + (i+1) +  "行岗位名称不能为空！");
            }
            JsonResult<Role> roleJsonResult = userClient.getRoleInfoByName(postName, departmentJsonResult.getData().getId(),null,null);
            if(roleJsonResult.getData().getId() == null){
                throw new BusinessException("第" + (i+1) + "该岗位:"+postName+"数据不存在！");
            }
            String username = jsonObj.getString("username");
            if(StringUtils.isEmpty(username)){
                throw new BusinessException("第" + (i+1) +  "用户名（工号）不能为空！");
            }
            JsonResult userIsOnly = userClient.userIsOnly(username, null, null);
            if("false".equals(userIsOnly.getData().toString())){
                throw new BusinessException("第" + (i+1) +"行用户名（工号）必须唯一，该工号：" +username+ "已存在！");
            }
            String nickname = jsonObj.getString("nickname");
            if(StringUtils.isEmpty(nickname)){
                throw new BusinessException("第" + (i+1) +  "姓名不能为空！");
            }
            String phone = jsonObj.getString("phone");
            if(StringUtils.isEmpty(phone)){
                throw new BusinessException("第" + (i+1) +  "手机号不能为空！");
            }
            JsonResult phoneIsOnly = userClient.userIsOnly(null, phone, null);
            if("false".equals(phoneIsOnly.getData().toString())){
                throw new BusinessException("第" + (i+1) +"行手机号必须唯一，该手机号：" +phone+ "已存在！");
            }
            String sex = jsonObj.getString("sex");
            if(StringUtils.isEmpty(sex)){
                throw new BusinessException("第" + (i+1) +  "性别不能为空！");
            }
            User user = new User();
            user.setCompanyInfoId(companyJsonResult.getData().getId());
            user.setDepartmentId(departmentJsonResult.getData().getId());
            user.setPostId(roleJsonResult.getData().getId());
            user.setRoleIds(roleJsonResult.getData().getId().toString());
            user.setUsername(username);
            user.setNickname(nickname);
            user.setPhone(phone);
            user.setSex(Integer.valueOf(sex));
            user.setIsJob(User.IsJob.job);
            user.setEnterpriseCode(companyJsonResult.getData().getMark());
            JsonResult result = userClient.addUser(user);
            if (result.getCode() != Result.Code.SUCCESS.getCode()) {
                throw new BusinessException(result.getMsg());
            }
        }

    }

    @Override
    public void syncUserInfo(EnterpricceIdVO enterpricceIdVo) throws IOException {

    }

    public static void main(String[] args) {
        String desSign = DigestUtil.md5Hex("123456");
        String desSign2= DigestUtil.md5Hex("companyName" +"departmentName" +"postName" +"username" + desSign);
        System.out.println(desSign);
        System.out.println(desSign2);
    }
}
